package org.example.listenerorder.task;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.poi.ss.usermodel.Workbook;
import org.example.listenerorder.model.OrderCementVO;
import org.example.listenerorder.model.OrderVO;
import org.springframework.util.ResourceUtils;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.*;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class printOrder {
    //获取打印机
    public static PrintService getPrinter(){
        PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
        if(!Objects.isNull(ps)){
            return ps;
        }
        return null;
    }
    //渲染打印模板
    public static InputStream renderTemplate(OrderVO o) throws IOException {
        //渲染模板
        TemplateExportParams p = new TemplateExportParams("static/template.xlsx");
        Map<String,Object> m = new HashMap<>();
        m.put("orderId",o.getOrderId());
        m.put("nickname",o.getNickname());
        m.put("createTime",o.getCreateTime());
        m.put("remark", StrUtil.cleanBlank(o.getRemark()));
        m.put("carLicense",o.getCarLicense());
        m.put("list",o.getOrderDetails());
        m.put("driverName",o.getDriverName());
        m.put("driverPhone",o.getDriverPhone());
        m.put("total",o.getOrderDetails().stream().mapToDouble(OrderCementVO::getCementWeight).sum());
        org.apache.poi.ss.usermodel.Workbook w = ExcelExportUtil.exportExcel(p,m);
        PoiMergeCellUtil.mergeCells(w.getSheetAt(0),6+o.getOrderDetails().size(),2,3,4,5,6);
//        URL url1 = ResourceUtils.getURL("classpath:static");
//        File file = new File(url1.getPath()+"/temp.xlsx");
//        if(file.exists()){
//          file.delete();
//        }
//        file.createNewFile();
//        //写入到文件
//        FileOutputStream fout = new FileOutputStream(file.getAbsolutePath());
//        w.write(fout);
//        fout.close();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        w.write(bos);
        w.close();
//        转为FileOutputStream
        byte[] byteArray = bos.toByteArray();
        InputStream b = new ByteArrayInputStream(byteArray);
        bos.close();
        return b;
//        FileOutputStream fouts = new FileOutputStream(file.getAbsolutePath());
//        w.write(fouts);
//        fouts.close();
    }
    //使用spire打印
    //使用原生打印
    public static boolean awtPrint(String filePath,PrintService ps) throws PrinterException, IOException {
        PrinterJob job = PrinterJob.getPrinterJob();
        if(!Objects.isNull(ps)){
            job.setPrintService(ps);
            PageFormat pageFormat = getPageFormat();

            Book book = new Book();

            PDDocument document = PDDocument.load(new File(filePath));
            book.append(new PDFPrintable(document), pageFormat, 1);
            job.setPageable(book);
            job.print();
            return true;
        }
        return false;
    }

    private static PageFormat getPageFormat() {
        Paper paper = new Paper();
        int width = 215;
        int height = 170;
        // 设置打印纸张大小
        paper.setSize(width,height); // 1/72 inch
        // 设置边距，单位是像素，10mm边距，对应 28px
        int marginLeft = 1;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        // 设置打印位置 坐标
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        return pageFormat;
    }

    public static boolean spirePrint(InputStream stream,PrintService ps){
       com.spire.xls.Workbook  workbook = new com.spire.xls.Workbook();
        try {

            workbook.loadFromStream(stream);
            PrinterJob printerJob = PrinterJob.getPrinterJob();
            printerJob.setPrintService(ps);
            PageFormat pageFormat  = printerJob.defaultPage();

            //Return a copy of the Paper object associated with this PageFormat.
            Paper paper = pageFormat .getPaper();

            //Set the imageable area of this Paper.
            paper.setImageableArea(0,0,pageFormat .getWidth(),pageFormat .getHeight());

            //Set the Paper object for this PageFormat.
            pageFormat .setPaper(paper);

            //Set the number of copies
            printerJob .setCopies(1);
            //Call painter to render the pages in the specified format
            printerJob .setPrintable(workbook,pageFormat);
            printerJob.print();
            return true;
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}
